package cn.gdcp.automatic_image_switching;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private ImageView imgZyl;
    private Button btnNext;
    private int zylimgs[]={R.drawable.zyl1,R.drawable.zyl2,R.drawable.zyl3,R.drawable.zyl4,R.drawable.zyl5};
    private int index=0;
    // Handler消息机制, 此时的handler是空值
    private Handler handler;
    private final int MSG_CHANGE_ZYL=1001;
    //判断是否处于暂停状态
    private boolean isPause=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgZyl=findViewById(R.id.zhuyilong);
        btnNext=findViewById(R.id.btnNext);

        //初始化handler
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if(message.what==MSG_CHANGE_ZYL){
                    index=(index+1)%zylimgs.length;
                    imgZyl.setImageResource(zylimgs[index]);
                    return true;
                }
                return false;
            }
        });

        // 改用线程，自动切换图片
        //Thread子线程, 在子线程中不可以修改主线程创建的view
        //需要使用消息机制  告诉主线程更新
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(2000); //每隔2秒切换一次
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }

                    if (!isPause){
                        //消息机制
                        Message message=new Message();
                        message.what=MSG_CHANGE_ZYL;
                        handler.sendMessage(message);
                        // 打印日志
                        Log.e("MainActivity","send change message");
                    }
                }
            }
        }).start(); // 让线程跑起来

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPause=!isPause;
            }
        });
    }
}
